package com.itheima.health.controller.mobile;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RedisMessageConstant;
import com.itheima.health.pojo.Order;
import com.itheima.health.result.Result;
import com.itheima.health.service.OrderService;
import com.itheima.health.util.AliSmsUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController("MobileOrderController")
@RequestMapping("/mobile/order")
@Api(tags = "用户端-套餐相关接口")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        log.info("预约下单:{}", map);
        String telephone = (String) map.get("telephone");
        Map redisMap = (Map) redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String code = (String) redisMap.get(RedisConst.VALIDATE_CODE_PREFIX);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
        if (code != null && validateCode != null && code.equals(validateCode)) {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }

//                AliSmsUtil aliSmsUtil = null;
//                try {
//                    aliSmsUtil.sendMess(telephone,"8888");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

            return result;
        } else {
            return new Result(false,MessageConst.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        log.info("查询预约订单:{}", id);
        Map map = null;
        try {
            map = orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_ORDER_FAIL);
        }
        return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,map);
    }

}
